package com.ala4.oxcafe.boot.handler;

import com.ala4.oxcafe.boot.exception.LoginUserNotFoundException;
import com.ala4.oxcafe.boot.exception.ObtainUserException;
import com.ala4.oxcafe.boot.exception.SoloLoginException;
import com.ala4.oxcafe.common.utils.ExceptionUtil;
import com.ala4.oxcafe.common.utils.IpAddressUtil;
import com.ala4.oxcafe.common.utils.ResponseWriter;
import com.ala4.oxcafe.domain.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authorization.AuthorizationDeniedException;

/**
 * 鉴权失败处理
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/12 14:01
 */
@Slf4j
public class AuthenticationFailureEntryPoint {


    /**
     * 认证与鉴权失败回调
     *
     * @param request   当前请求
     * @param response  当前响应
     * @param throwable 具体的异常信息
     */
    public static void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Throwable throwable) {

        log.error("认证鉴权失败:{},{},{}", IpAddressUtil.getClientIp(request), request.getRequestURI(), throwable.getMessage(), throwable);

        String requestURI = request.getRequestURI();
        R<?> fail = R.fail(throwable.getMessage(), requestURI);

        // 默认401 未授权 需要跳登录页面
        fail.setStatus(HttpStatus.UNAUTHORIZED.value());
        fail.setError(throwable.getMessage());
        fail.setMessage("用户未登录,请先登录");

        if (throwable instanceof LoginUserNotFoundException loginUserNotFoundException) {
            // 前端406 登录用户不存在 需要跳登录页面
            fail.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
            fail.setMessage(loginUserNotFoundException.getMessage());
        }
        if (throwable instanceof SoloLoginException soloLoginException) {
            // 406 用户在其他终端登录了 需要跳登录页面
            fail.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
            fail.setMessage(soloLoginException.getMessage());
        }
        if (throwable instanceof AuthorizationDeniedException) {
            // 403 API接口无权限-权限不足 不需要跳登录页面
            fail.setStatus(HttpStatus.FORBIDDEN.value());
            fail.setMessage("访问用户无权限");
        }

        // 系统错误
        if (throwable instanceof ObtainUserException obtainUserException) {
            // 500
            fail.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            fail.setMessage(obtainUserException.getMessage());
            fail.setError(ExceptionUtil.getFullExceptionChain(obtainUserException));
        }
        // 写出
        ResponseWriter.write(response, fail);
    }
}
